const {NAME_OR_PASSWORD_IS_NOT_REQUIRED,USER_ALREADY_EXISIS} = require("../contants/error-types")
const service = require("../service/user.service");


const {md5password} = require("../utils/password-handle")

//验证用户密码中间件
const verifyUser = async (ctx,next) => {
  //1.获取用户名和密码
  const {name,password} = ctx.request.body

  //2. 判断用户名或密码不为空
  if(!name || !password){
    const error = new Error(NAME_OR_PASSWORD_IS_NOT_REQUIRED);
    return ctx.app.emit('error',error,ctx)
  }

  //3.判断这次注册的用户名是没有被注册过的
  const result = await service.getUserByName(name);
  if(result.length){
    const error = new Error(USER_ALREADY_EXISIS)
    return ctx.app.emit('error',error,ctx)
  }

  await next()
}

//密码加密中间件
const handlePassword = async (ctx,next) => {
  let {password} = ctx.request.body
  ctx.request.body.password = md5password(password);
  await next()

}

module.exports = {
  verifyUser,
  handlePassword
}